    /*
 * ReaderAPI.fx
 *
 * Created on Mar 31, 2010, 10:54:43 AM
 */

package fxgreader;
import javafx.io.http.HttpRequest;
import javafx.io.http.HttpHeader;
import javafx.data.pull.Event;
import javafx.data.pull.PullParser;
import java.util.ArrayList;
import java.util.Map;

/**
 * @author perkintang
 */
public def STAR : String = "starred";
public def LIKE : String = "like";
public def SHARE : String = "broadcast";
public def READ : String = "read";
public def ADD : String = "a";
public def REMOVE : String = "r";
public class ReaderAPI {
public var perFetch : Integer = 10;
public var email : String;
public var passwd : String;
//public var imagearray : ArrayList;
public var articles : ArrayList;
public var unreadCount : Integer;
var sid : String = "";
var auth : String = "";
var userid : String = "";
var token : String = "";
public var tags : String[] = [];
public var continuationCode : String = "";
public var onLogin : function();
public var onLoginFailed : function();
public var onGetUnreadCount : function();
public function login(){
    var sidrequest: HttpRequest = HttpRequest {
                                location: "https://www.google.com/accounts/ClientLogin?service=reader&Email={email}&Passwd={passwd}"
                                method: HttpRequest.GET
                                onInput: function(is: java.io.InputStream) {
                                            try {
                                                var rtn : String[] = HttpUtil.getSIDAndAuth(is);
                                                sid = rtn[0];
                                                println("SID : {sid}");
                                                auth = rtn[1];
                                                println("Auth : {auth}");
                                                getToken();
                                                getUserID();
                                                getTags();
//                                                getReading();
                                                onLogin();
                                            } finally {
                                                is.close();
                                            }
                                           }
                                onException: function(ex: java.lang.Exception) {
                                                onLoginFailed();
                                                println("onException - exception: {ex.getClass()} {ex.getMessage()}");
                                             }
                                };
    sidrequest.start();
}
var onGetToken:function();
public function getToken(){
    var cookierequest: HttpRequest = HttpRequest {
                                location: "http://www.google.com/reader/api/0/token"
                                method: HttpRequest.GET
                                headers: [
                                    HttpHeader {
                                    name: "Cookie";
                                    value: "SID={sid}";
                                    }
                                    HttpHeader {
                                    name: "Authorization";
                                    value: "GoogleLogin auth={auth}";
                                    }
                                ];
                                onInput: function(is: java.io.InputStream) {
                                            try {
//                                                  parser(is);
//                                                var conv = new HttpUtil(is);
                                                var s = HttpUtil.convertStreamToString(is);
                                                token = s;
                                                println("token : {s}");
                                                onGetToken();
//                                                getReading();
                                            } finally {
                                                is.close();
                                            }
                                }
                                onException: function(ex: java.lang.Exception) {
                                                println("onException - exception: {ex.getClass()} {ex.getMessage()}");
                                             }
                                };
    cookierequest.start();
}
function getUserID(){
        var cookierequest: HttpRequest = HttpRequest {
                                location: "https://www.google.com/reader/api/0/user-info"
                                method: HttpRequest.GET
                                headers: [
                                    HttpHeader {
                                    name: "Cookie";
                                    //    * Name: SID
                                    //    * Value: [your SID]
                                    //    * Path: /
                                    //    * Domain: .google.com
                                    value: "SID={sid}";
                                    }
                                    HttpHeader {
                                    name: "Authorization";
                                    value: "GoogleLogin auth={auth}";
                                    }
                                ];
                                onInput: function(is: java.io.InputStream) {
                                                  def parser = PullParser {
                                                                    documentType: PullParser.JSON;
                                                                    input: is;
                                                                    onEvent: function(event: Event) {

                                                                if (event.type == PullParser.END_VALUE) {
                                                                        if (event.name == "userId") {
                                                                            userid = event.text;
                                                                        }
                                                                };
                                                  }};
                                                  parser.parse();
                                                  is.close();
                                                  println("userid : {userid}");
//                                                var conv = new HttpUtil(is);
//                                                var s = conv.convertStreamToString();
//                                                println("userinfo : {s}");
                                };
                                onException: function(ex: java.lang.Exception) {
                                                println("onException - exception: {ex.getClass()} {ex.getMessage()}");
                                             }
                                };
    cookierequest.start();
}
public function getTags(){
        //https://www.google.com/reader/api/0/tag/list?output=json
        var tagsrequest: HttpRequest = HttpRequest {
                                location: "https://www.google.com/reader/api/0/tag/list?output=json"
                                method: HttpRequest.GET
                                headers: [
                                    HttpHeader {
                                    name: "Cookie";
                                    //    * Name: SID
                                    //    * Value: [your SID]
                                    //    * Path: /
                                    //    * Domain: .google.com
                                    value: "SID={sid}";
                                    }
                                    HttpHeader {
                                    name: "Authorization";
                                    value: "GoogleLogin auth={auth}";
                                    }
                                ];
                                onInput: function(is: java.io.InputStream) {
                                              def parser = PullParser {
                                                                documentType: PullParser.JSON;
                                                                input: is;
                                                                onEvent: function(event: Event) {
                                                                            if (event.type == PullParser.END_VALUE and event.name == "id") {
                                                                                        var tag = event.text.substring(event.text.lastIndexOf("/")+1);
                                                                                        insert tag into tags;
                                                                            };
                                                                         }
                                                            };
                                              parser.parse();
                                              is.close();
                                              println(tags);
                                };
                                onException: function(ex: java.lang.Exception) {
                                                println("onException - exception: {ex.getClass()} {ex.getMessage()}");
                                             }
                                };
    tagsrequest.start();
}
public function getUnreadCount(){
    //http://www.google.com/reader/api/0/unread-count?output=json
            var tagsrequest: HttpRequest = HttpRequest {
                                location: "http://www.google.com/reader/api/0/unread-count?output=json"
                                method: HttpRequest.GET
                                headers: [
                                    HttpHeader {
                                    name: "Cookie";
                                    //    * Name: SID
                                    //    * Value: [your SID]
                                    //    * Path: /
                                    //    * Domain: .google.com
                                    value: "SID={sid}";
                                    }
                                    HttpHeader {
                                    name: "Authorization";
                                    value: "GoogleLogin auth={auth}";
                                    }
                                ];
                                onInput: function(is: java.io.InputStream) {
                                              def parser = PullParser {
                                                                documentType: PullParser.JSON;
                                                                input: is;
                                                                onEvent: function(event: Event) {
                                                                            if(event.type == PullParser.END_VALUE and event.name == "max" ){
                                                                                    unreadCount = event.integerValue;
                                                                            }
                                                                         }
                                                            };
                                              parser.parse();
                                              is.close();
                                              onGetUnreadCount();
                                };
                                onException: function(ex: java.lang.Exception) {
                                                println("onException - exception: {ex.getClass()} {ex.getMessage()}");
                                             }
                                };
    tagsrequest.start();
}
public var onGetReading : function();
public function getReading():Boolean{
    if(continuationCode == "loading"){
            return false;
    }
    var userrequest: HttpRequest = HttpRequest {
                                location: "https://www.google.com/reader/atom/?n={perFetch}&c={continuationCode}"
                                method: HttpRequest.GET
                                headers: [
                                    HttpHeader {
                                    name: "Cookie";
                                    //    * Name: SID
                                    //    * Value: [your SID]
                                    //    * Path: /
                                    //    * Domain: .google.com
                                    value: "SID={sid}";
                                    }
                                    HttpHeader {
                                    name: "Authorization";
                                    value: "GoogleLogin auth={auth}";
                                    }
                                ];
                                onInput: function(is: java.io.InputStream) {
                                            try {
                                                  var rtn : Map = HttpUtil.parseAtom(is) as Map;
                                                  articles = rtn.get("artics") as ArrayList;
                                                  continuationCode = rtn.get("continuation") as String;

                                            } finally {
                                                is.close();
                                            }
                                            onGetReading();
                                           }
                                onException: function(ex: java.lang.Exception) {
                                                println("onException - exception: {ex.getClass()} {ex.getMessage()}");
                                             }
                                };
    userrequest.start();
    continuationCode = "loading";
    return true;
}
public var onGetReadingByLable : function(label : String);
public function getReadingByLable(label : String){
    if(continuationCode == "loading"){
            return false;
    }
    var userrequest: HttpRequest = HttpRequest {
                                location: "http://www.google.com/reader/atom/user/-/label/{label}?n={perFetch}&c={continuationCode}"
                                method: HttpRequest.GET
                                headers: [
                                    HttpHeader {
                                    name: "Cookie";
                                    //    * Name: SID
                                    //    * Value: [your SID]
                                    //    * Path: /
                                    //    * Domain: .google.com
                                    value: "SID={sid}";
                                    }
                                    HttpHeader {
                                    name: "Authorization";
                                    value: "GoogleLogin auth={auth}";
                                    }
                                ];
                                onInput: function(is: java.io.InputStream) {
                                            try {
                                                  var rtn : Map = HttpUtil.parseAtom(is) as Map;
                                                  articles = rtn.get("artics") as ArrayList;
                                                  continuationCode = rtn.get("continuation") as String;

                                            } finally {
                                                is.close();
                                            }
                                            onGetReadingByLable(label);
                                           }
                                onException: function(ex: java.lang.Exception) {
                                                println("onException - exception: {ex.getClass()} {ex.getMessage()}");
                                             }
                                };
    userrequest.start();
    continuationCode = "loading";
    return true;
}
public var onMarkSuccess : function(article : Article):Void;
public var onMarkFailed : function(article : Article):Void;
public function markArticle(article : Article, mark : String, type : String, retry : Boolean):Void{
    def postContent: String = "{type}=user/{userid}/state/com.google/{mark}&async=true&i={article.getId()}&pos=0&T={token}";
    var userrequest: HttpRequest = HttpRequest {
                                location: "https://www.google.com/reader/api/0/edit-tag?client=scroll"
                                method: HttpRequest.POST
                                headers: [
                                    HttpHeader {
                                    name: "Cookie";
                                    //    * Name: SID
                                    //    * Value: [your SID]
                                    //    * Path: /
                                    //    * Domain: .google.com
                                    value: "SID={sid}";
                                    }
                                    HttpHeader {
                                    name: "Authorization";
                                    value: "GoogleLogin auth={auth}";
                                    }
                                ];
                                onOutput: function(os: java.io.OutputStream) {
                                    try {
                                        os.write(postContent.getBytes());
                                    } finally {
                                        os.close();
                                    }
                                }
                                onInput: function(is: java.io.InputStream) {
                                    try {
                                        var s = HttpUtil.convertStreamToString(is);
                                        println("{mark} result : {s}");
                                        if(s.trim().equalsIgnoreCase("OK")){
                                                onMarkSuccess(article);
                                        }else{
                                                onMarkFailed(article);
                                        }
                                    } finally {
                                        is.close();
                                    }
                                }
                                onException: function(ex: java.lang.Exception) {
                                                println("onException - exception: {ex.getClass()} {ex.getMessage()}");
                                                if(retry){
                                                    onMarkFailed(article);
                                                }
                                             }
                                };
    onMarkFailed = function(article){
            onGetToken = function(){
                    //just try once?
                    markArticle(article, mark, type,false);
            };
            getToken();
    };
    userrequest.start();
}
public function getFullText(link : String, callBack : function(is: java.io.InputStream)){
    var request: HttpRequest = HttpRequest {
                                location: link
                                method: HttpRequest.GET
                                onInput: function(is: java.io.InputStream) {
                                            try {
                                                  callBack(is);

                                            } finally {
                                                is.close();
                                            }
                                            onGetReading();
                                           }
                                onException: function(ex: java.lang.Exception) {
                                                println("onException - exception: {ex.getClass()} {ex.getMessage()}");
                                             }
                                };
    request.start();
}
}
